import { useState } from 'react';

import MemberManager from '../api/member/member-manager';

export function useLoadScholar() {
    const [loading, setLoading] = useState(false);
    const [items, setItems] = useState([]);
    const [page, setPage] = useState(0);
    const [hasNextPage, setHasNextPage] = useState(false);
    const [error, setError] = useState<{ code: number; message: string }>(undefined);

    async function loadMore() {
        setLoading(true);
        try {
            const result = await MemberManager.getList(page);

            const { hasMore, members } = result;
            setItems((current) => [...current, ...(members || [])]);
            setHasNextPage(hasMore);
            hasMore && setPage(page + 1);
        } catch (err) {
            setError(err);
        } finally {
            setLoading(false);
        }
    }

    return { loading, items, hasNextPage, error, loadMore };
}
